package com.cultusoft.groovin.plugins.fitnesse;

import com.cultusoft.groovin.plugins.build.ProjectClasspathCreator
import com.cultusoft.groovin.plugins.project.LibraryProject
import com.cultusoft.groovin.log.GroovinLogger
import com.cultusoft.groovin.configuration.Configuration
import com.cultusoft.groovin.plugins.build.ProjectDependencyDownloader


class FitnesseTestRunner {
    def neededPackages = [new LibraryProject(group:"org/fitnesse", id:"fitnesse", version:"20060719") ] as List

	def testToRun
    def logger = new GroovinLogger(this)
	
 	public void run() {
        downloadNeededPackages()
		runFitnesseTest()
 	}

    def downloadNeededPackages() {
        new ProjectDependencyDownloader().downloadLibraries(neededPackages)
    }  
 	
	private void runFitnesseTest() {
        def configuration = new Configuration()
		def fitnesseProperties = configuration.getFitnesseProperties()
		
		def myClasspath = new ProjectClasspathCreator().createClasspathFromProjects(configuration.getProjects())
		
		File fitnesseReportFolder = new File(fitnesseProperties.logDirectory)
		
		if (!fitnesseReportFolder.exists()) {
		    fitnesseReportFolder.mkdir()		    
		}
		
		def testResultsFilePath = new File(fitnesseReportFolder, testToRun +".html").getPath()
		def testOutputFilePath = new File(fitnesseReportFolder, testToRun +".log").getPath()
		logger.log "Running test: " + testToRun
        logger.debug "using classpath $myClasspath"
		logger.log "Test results will be saved to $testResultsFilePath"
		logger.log "Test output will be saved to $testOutputFilePath"
		
		def ant = new AntBuilder()
		ant.java( classname:"fitnesse.runner.TestRunner",
				classpath:myClasspath,
				resultproperty:"returnCode",
				failonerror:false,
				fork:true,
				output:testOutputFilePath
				) {
			arg(value:"-html")
			arg(value:testResultsFilePath)
			arg(value:fitnesseProperties.getHostname())
			arg(value:fitnesseProperties.getPort())
			arg(value:testToRun)
		}
		
		def returnCode = ant.properties.antProject.getProperty("returnCode")
		
		if (!returnCode.equals("0")) {
			throw new Exception ("Fitnesse tests have failed.")
		} else {
			logger.log("Fitnesse tests have passed")
		}
	
 	}

}
